/**
 * tournote file;
 * company:junqitecch
 * author:xuzuiotao
 * 游迹功能采用mongo存储
 * mongodb TourNote{
          {
           ID:
           userID:
           title:
           coverURL:
           followedNum:
           commentedNum:
           praisedNum:
           content:[{},{}];
           createTime:
           updateTime:
           latestTime:
           comments:[{}]
           users:[];
          }

 *  
 *
 */



var mongoClient = require('mongodb').MongoClient;
consts = require('../consts');
var tournote_user = require('./tournote_user');
var tournote_comment = require('./tournote_comment');


function getNextTourNote_Value(db, callback){
	console.log('mmmaaa');
	
	   db.collection('ids').findAndModify(
		{'_id': 'autoID' },
		[['_id','asc']],   
		{$inc:{'tournote_value':1,'timeline_value':1}},
		{'new':true,upsert:true},
		callback);

}

/*
 * 获取所有的游迹列表
 */

function listTourNote(baseLine,direction,count,callback){

	console.log("tournote");
	var url = consts.MongoURL;// 'mongodb://59.110.54.101:2700/tournote';  
	mongoClient.connect(url,consts.MongoOptions, function(err, db) {  
	    if (err)  
	    {  
	    	error = new Error();
	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;
	    	
	        console.log(err);
	        if(callback){
	        	callback(error,null);
	        }
	    }  
	    else  
	    {  
	    	var col = db.collection("tournote"); 
	    	var whereStr =null;
	    	if(baseLine!==0){
	    		if(direction>0){
	    			whereStr={'baseLine':{$gt:baseLine}};
	    		}else{
	    			whereStr={'baseLine':{$lt:baseLine}};
	    		}
	  
	    	}
	    	  col.find(whereStr,{'_id':1,'title':1,'userID':1,'readNum':1,'commentedNum':1,'praisedNum':1,'coverURL':1,'baseLine':1}).hint({'baseLine':-1}).limit(count).toArray(function(err, result){
	    	    if(err)
	    	    {
	    	        console.log('Error:'+ err);
		     	  	error = new Error();
	
	    	    	error.number= consts.Error.ERROR_GENERAL;
	    	    	error.message=consts.Message.UNKNOWN;
	    	    	
	    	        if(callback){
	    	        	callback(error,null);
	    	        }
	    	        
	    	    	db.close();

	    	        return;
	    	    }
	    	    first=0;
	    	    last=0;
	    	    count=result.length;
	    	    if(result.length>0){
	    	        first=result[0].baseLine;
	    	        last=result[result.length-1].baseLine;
	    	    }
	    	    
	    	    var userIDs = [];
	    	    var dic = [];
	    	    for(i=0;i<result.length;i++){
	    	    	dic[result[i].userID+'']=result[i].userID;
//	    	    	delete result[i].baseLine;
	    	    }
	    	    for (var key in dic) {
	    	    	userIDs.push(dic[key]);
	            }
	    	    tournote_user.batchUsers(userIDs,db,function(error,users){
	    	    	var content= {};
	  	    	    content.first=first;
	  	    	    content.last=last;
	  	    	    var array= [];
	  	    	    if(users){
	  	    	    	for(i=0;i<users.length;i++)
	  	    	    		array[users[i].userID+'']=users[i];
	  	    	    }
	  	    	    if(result){
	  	    	    	for(i=0;i<result.length;i++){
	  	    	    		result[i].user=array[result[i].userID+''];
	  	    	    		delete result[i].userID;
	  	    	    	}
	  	    	    }
	  	    	    //if(users!=null)content.users=users;
	  	    	    content.count=count;
	  	    	    if(count>0){
	  		    	    content.items=result;
	  	    	    }
	    	    	db.close();

	  	    	    if(callback){
	  		        	  callback(null,content);
	  	    		}
	    	    });
	    	  });
	    }  
	});  

}


/*
 * 获取某个用户的游迹列表
 */
function detailTourNote(ID,userID,callback){

	var url =  consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
	mongoClient.connect(url,consts.MongoOptions, function(err, db) {  
	    if (err)  
	    {  
	    	error = new Error();
	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;
	    	
	        console.log(err);
	        if(callback){
	        	callback(error,null);
	        }
	    }  
	    else  
	    {  
	    	var col = db.collection("tournote"); 
	    	whereStr ={'_id':ID};

	    	col.findAndModify(whereStr,[],{$inc:{'readNum':1}},function(err, result){
	    	    if(err ||result.value===null || typeof(result.value)==='undefined')
	    	    {
	    	        console.log('Error:'+ err);
		     	  	error = new Error();

		     	  	error.number= consts.Error.ERROR_GENERAL;
	    	    	error.message=consts.Message.UNKNOWN;
	    	    	db.close();
	    	        if(callback){
	    	        	callback(error,null);
	    	        }
	    	        return;
	    	    }
	    	   
	    	    colpraise= db.collection('tournote_praise');

	    	    colpraise.findOne({'userID':userID,'contID':ID},function(er,obj){
	    	    
	    	    	var praised=0;
	    	    	if(obj===null && userID>0 ){
	    	    		praised=1;
	    	    	}else if(obj!==null){
	    	    		praised=2;
	    	    	}

	    	    	tournote_comment.listCommenttoData(ID,0,0,10,db,result.value,true,function(err,content){
	    	    		
	    	    		var shareParam={};
	    	    		shareParam.ver=0;
	    	    		shareParam.op=consts.Service.TOURNOTE_DETAIL;
	    	    		var dataID={};
	    	    		dataID._id=ID;
	    	    		shareParam.data=JSON.stringify(dataID);
	    	    		shareParam=Buffer.from(JSON.stringify(shareParam));
	    	    		
	    	    		url = consts.Url.MOBILE+'note_detail.html?param='+shareParam.toString('base64');
		    	    	if(err || content===null){
		 	    	        console.log('Error:'+ err);
		 		     	  	error = new Error();
		 		     
		 	    	        content= {};
		 	    	        content.object=result.value;
		 	    	    	content.object.shareURL=url;//'http://mobile.xinmayoujiang.com';
			    	    	db.close();

		 	    	        if(callback){
		 	    	        	callback(null,content);
		 	    	        }
		 	    	        return;
		 	    	    }else{
		 	    	    
		 	    	    	delete result.value.baseLine;
		 	    	    	content.object=result.value;
		 	    	    	content.object.shareURL=url+'';//'http://mobile.xinmayoujiang.com';
			    	    	db.close();

		 		     	  	if(praised>0)content.praised=praised;

		 	    	    	 if(callback){
			  		        	  callback(null,content);
			  	    		}
		 	    	    }
		    
		    	    });
		    	
		    	});
	    	  
	    	});
	    	    
	    }  
	
	});  

}

/*
 * 获取某个用户的游迹列表
 */
function listTourNoteByUserID(userID,baseLine,direction,count,callback){

	var url =  consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
	mongoClient.connect(url,consts.MongoOptions, function(err, db) {  
	    if (err)  
	    {  
	    	error = new Error();
	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;
	    	
	        console.log(err);
	        if(callback){
	        	callback(error,null);
	        }
	    }  
	    else  
	    {  
	    	var col = db.collection("tournote"); 
	    	whereStr ={'userID':userID};
	    	if(baseLine!==0){
	    		if(direction>0){
	    			whereStr={'userID':userID,'baseLine':{$gt:baseLine}};
	    		}else{
	    			whereStr={'userID':userID,'baseLine':{$lt:baseLine}};
	    		}
	  
	    	}
	    	  col.find(whereStr,{'_id':1,'title':1,'userID':1,'readNum':1,'commentedNum':1,'praisedNum':1,'coverURL':1,'baseLine':1}).hint({'baseLine':-1}).limit(count).toArray(function(err, result){
	    	    if(err)
	    	    {
	    	        console.log('Error:'+ err);
		     	  	error = new Error();
	
	    	    	error.number= consts.Error.ERROR_GENERAL;
	    	    	error.message=consts.Message.UNKNOWN;
	    	    	
	    	        if(callback){
	    	        	callback(error,null);
	    	        }
	    	    	db.close();

	    	        return;
	    	    }
	    	    first=0;
	    	    last=0;
	    	    count=result.length;
	    	    if(result.length>0){
	    	        first=result[0].baseLine;
	    	        last=result[result.length-1].baseLine;
	    	    }
	    	    for(i=0;i<result.length;i++){
//	    	    	delete result[i].baseLine;
	    	    }
	    	    
	    	    content= {};
	    	    content.first=first;
	    	    content.last=last;
	    	    content.count=count;
	    	    if(count>0){
		    	    content.items=result;
		    	    tournote_user.getUser(userID,db, function(error,user){
		    	    	if(user){
		    	    		for(i=0;i<result.length;i++){
		    	    			result[i].user=user;
		    	    			delete result[i].userID;
		    	    		}
		    	    	}
		    	    	db.close();

		    	    	if(callback){
		    	    		callback(null,content);
		    		
		    	    	}
		    	    });
		    	    
	    	    }else{
	    	    	db.close();
	    	    	if(callback){
	    	    		callback(null,content);
	    		
	    	    	}
	    	    }
	    	  });
		
	    }  
	});  

}


/*
 * 删除游迹
 */
function deleteTourNote(userID,_id,callback){
	
	var url =  consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
	mongoClient.connect(url,consts.MongoOptions, function(err, db) {  
	    if (err)  
	    {  
	    	error = new Error();
	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;
	    	
	        console.log(err);
	        if(callback){
	        	callback(error,null);
	        }
	    }  
	    else  
	    {  
	    	
		    var col = db.collection("tournote"); 
		    	
		    col.remove({'_id':_id,'userID':userID},function(errr,result){
		    	console.log(result.result);
		    	if(errr||result.result.n===0){
	    			error = new Error();
	    	    	error.number= consts.Error.ERROR_GENERAL;
	    	    	error.message=consts.Message.UNKNOWN;
	    	    	db.close();
	    	    	console.log(errr);
	    		    if(callback){
	    		        	callback(error,null);
	    		    }
	    		    return;
	    		 }
	    		
    	    	db.close();

	    		if(callback){
  		        	  callback(null,null);
	    		
	    		}
		        console.log('bbbbbb');
	    		    
	    	});
	   
	    }  
	});  

}



/*
 * 添加游迹
 */
function insertTourNote(user,tournote,callback){
	
	var url =  consts.MongoURL;//'mongodb://59.110.54.101:2700/tournote';  
	mongoClient.connect(url,consts.MongoOptions, function(err, db) {  
	    if (err)  
	    {  
	    	error = new Error();
	    	error.number= consts.Error.ERROR_GENERAL;
	    	error.message=consts.Message.UNKNOWN;
	    	
	        console.log(err);
	        if(callback){
	        	callback(error,null);
	        }
	    }  
	    else  
	    {  
	    	var id= getNextTourNote_Value(db,function(err,obj){
	    		
	    		if(err){
	    			
	    			error = new Error();

	    	    	error.number= consts.Error.ERROR_GENERAL;
	    	    	error.message=consts.Message.UNKNOWN;
	    	    	
	    	        if(callback){
	    	        	callback(error,null);
	    	        }
	    	    	db.close();

	    			return;
	    		}
	    		console.log(obj);

	    		tournote._id=obj.value.tournote_value;
		    	tournote.userID=user.userID;
		        t=Date.now();
		                     
		        tournote.createTime = t;
		        tournote.updateTime = t;
		        tournote.baseLine=obj.value.timeline_value;
		        tournote.readNum=0;
		        tournote.commentedNum=0;
		        tournote.praisedNum=0;
		        console.log('aaaaaaaaaa');
		    	var col = db.collection("tournote"); 
		    	
		    	col.save(tournote,[],function(errr,data){
	    		if(errr){
	    			error = new Error();
	    	    	error.number= consts.Error.ERROR_GENERAL;
	    	    	error.message=consts.Message.UNKNOWN;
	    	    	
	    	    	console.log(errr);
	    		    if(callback){
	    		        	callback(error,null);
	    		    }
	    		    
	    	    	db.close();

	    		    return;
	    		}
	    		
	    		var tuser= {};
	    		tuser._id=user.userID;
	    		tuser.userID=user.userID;
	    		tuser.iconURL=user.iconURL;
	    		tuser.nickName = user.nickName;
	    		
	    		
	    		tournote_user.insert(tuser,db,function(){
	    	    	db.close();
	    	    	
		    		if(callback){
	  		        	  callback(null,tournote);
		    		
		    		}
			        console.log('bbbbbb');
	    			
	    			
	    		});
	    	
	    		
	    	});
		    
	    	});
	   
	    }  
	});  

}

module.exports = {
	insertTourNote:insertTourNote,
	listTourNote:listTourNote,
	listTourNoteByUserID:listTourNoteByUserID,
	detailTourNote:detailTourNote,
	deleteTourNote:deleteTourNote,
 
};

